package zl.ordermanager.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import javax.servlet.http.HttpSession;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import zl.ordermanager.dao.SalesInvoiceDao;
import zl.ordermanager.dao.SalesOrderDao;
import zl.ordermanager.po.Tsalesinvoice;
import zl.ordermanager.po.Tsalesorder;
import zl.ordermanager.service.SalesInvoiceService;
import zl.ordermanager.utils.ConfigUtil;
import zl.ordermanager.vo.DataGrid;
import zl.ordermanager.vo.PageHelper;
import zl.ordermanager.vo.SalesInvoice;
import zl.ordermanager.vo.SessionInfo;
import zl.ordermanager.vo.Total;

@Service
public class SalesInvoiceServiceImpl implements SalesInvoiceService {

	@Autowired
	private SalesInvoiceDao salesInvoiceDao;

	@Autowired
	private SalesOrderDao salesOrderDao;

	@Override
	public DataGrid<SalesInvoice> dataGrid(HttpSession session, PageHelper pageHelper, Total total) {
		DataGrid<SalesInvoice> dataGrid = new DataGrid<SalesInvoice>();
		List<SalesInvoice> salesInvoiceList = new ArrayList<SalesInvoice>();
		Map<String, Object> params = new HashMap<String, Object>();
		if (pageHelper.getKeywords() != null && !pageHelper.getKeywords().isEmpty()) {
			params.put("keyword", "%%" + pageHelper.getKeywords() + "%%");
		}
		if (pageHelper.getCustomer() != null && !pageHelper.getCustomer().isEmpty()) {
			params.put("customer", "%%" + pageHelper.getCustomer() + "%%");
		}
		if (pageHelper.getInvoiceType() != null && !pageHelper.getInvoiceType().isEmpty()) {
			params.put("invoiceType", pageHelper.getInvoiceType());
		}
		if (pageHelper.getAbstractMonth() != null && !pageHelper.getAbstractMonth().isEmpty()) {
			params.put("abstractMonth", pageHelper.getAbstractMonth());
		}
		if (pageHelper.getInvoiceDate() != null && !pageHelper.getInvoiceDate().isEmpty()) {
			params.put("invoiceDate", pageHelper.getInvoiceDate());
		}
		String hql = " from Tsalesinvoice t ";
		List<Tsalesinvoice> tsalesinvoiceList = salesInvoiceDao.find(hql + whereHql(session, pageHelper)
				+ orderHql(pageHelper), params, pageHelper.getPageNum(), pageHelper.getNumPerPage());
		if (tsalesinvoiceList != null && tsalesinvoiceList.size() > 0) {
			for (Tsalesinvoice tsalesinvoice : tsalesinvoiceList) {
				SalesInvoice salesInvoice = new SalesInvoice();
				BeanUtils.copyProperties(tsalesinvoice, salesInvoice);
				salesInvoiceList.add(salesInvoice);
			}
		}
		dataGrid.setList(salesInvoiceList);
		dataGrid.setTotal(salesInvoiceDao.count("select count(*) " + hql + whereHql(session, pageHelper), params));

		total.setAmount(salesInvoiceDao.sum("select sum(t.amount) " + hql + whereHql(session, pageHelper), params));
		return dataGrid;
	}

	private String whereHql(HttpSession session, PageHelper pageHelper) {
		String whereString = "";
		if (pageHelper.getKeywords() != null && !pageHelper.getKeywords().isEmpty()) {
			whereString += " where (t.orderNo like :keyword ";
			whereString += " or t.customer like :keyword ";
			whereString += " or t.salesman like :keyword ";
			whereString += " or t.drawer like :keyword ";
			whereString += " or t.invoiceDate like :keyword ";
			whereString += " or t.invoiceNo like :keyword ";
			whereString += " or t.invoiceType like :keyword ";
			whereString += " or t.ai like :keyword ";
			whereString += " or t.orderAmount like :keyword ";
			whereString += " or t.amount like :keyword ";
			whereString += " or t.abstractMonth like :keyword ";
			whereString += " or t.remarks like :keyword) ";
		}

		if (pageHelper.getCustomer() != null && !pageHelper.getCustomer().isEmpty()) {
			if (whereString.isEmpty()) {
				whereString = "where (t.customer like :customer)";
			} else {
				whereString += " and (t.customer like :customer)";
			}
		}
		if (pageHelper.getInvoiceType() != null && !pageHelper.getInvoiceType().isEmpty()) {
			if (whereString.isEmpty()) {
				whereString = "where (t.invoiceType = :invoiceType)";
			} else {
				whereString += " and (t.invoiceType = :invoiceType)";
			}
		}
		if (pageHelper.getAbstractMonth() != null && !pageHelper.getAbstractMonth().isEmpty()) {
			if (whereString.isEmpty()) {
				whereString = "where (t.abstractMonth = :abstractMonth)";
			} else {
				whereString += " and (t.abstractMonth = :abstractMonth)";
			}
		}
		if (pageHelper.getInvoiceDate() != null && !pageHelper.getInvoiceDate().isEmpty()) {
			if (whereString.isEmpty()) {
				whereString = "where (t.invoiceDate = :invoiceDate)";
			} else {
				whereString += " and (t.invoiceDate = :invoiceDate)";
			}
		}

		String salesman = "";
		SessionInfo sessionInfo = (SessionInfo) session.getAttribute(ConfigUtil.getSessionInfoName());
		if (sessionInfo != null) {
			if (sessionInfo.getRole().equals("业务员")) {
				salesman = " (t.salesman = '" + sessionInfo.getRealname() + "')";
			}
		}

		if (!salesman.isEmpty()) {
			if (!whereString.isEmpty()) {
				whereString = whereString + " and " + salesman;
			} else {
				whereString = "where " + salesman;
			}
		}

		return whereString;
	}

	private String orderHql(PageHelper pageHelper) {
		String orderString = "";
		if (pageHelper.getOrderField() != null && !pageHelper.getOrderField().isEmpty()
				&& pageHelper.getOrderDirection() != null && !pageHelper.getOrderDirection().isEmpty()) {
			orderString = " order by t." + pageHelper.getOrderField() + " " + pageHelper.getOrderDirection();
		}
		return orderString;
	}

	@Override
	public SalesInvoice get(Integer id) {
		Tsalesinvoice tsalesinvoice = salesInvoiceDao.get(Tsalesinvoice.class, id);
		if (tsalesinvoice == null) {
			return null;
		}
		SalesInvoice salesInvoice = new SalesInvoice();
		BeanUtils.copyProperties(tsalesinvoice, salesInvoice);
		return salesInvoice;
	}

	@Override
	public SalesInvoice getByInvoiceNo(String invoiceNo) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("invoiceNo", invoiceNo);
		Tsalesinvoice tsalesinvoice = salesInvoiceDao
				.get("from Tsalesinvoice t where t.invoiceNo = :invoiceNo", params);
		if (tsalesinvoice == null) {
			return null;
		}
		SalesInvoice salesInvoice = new SalesInvoice();
		BeanUtils.copyProperties(tsalesinvoice, salesInvoice);
		return salesInvoice;
	}

	@Override
	public void add(SalesInvoice salesInvoice) throws Exception {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("invoiceNo", salesInvoice.getInvoiceNo());
		if (salesInvoiceDao.count("select count(*) from Tsalesinvoice t where t.invoiceNo = :invoiceNo", params) > 0) {
			throw new Exception("发票号已存在！");
		}

		String[] customers = salesInvoice.getCustomer().split(",");
		Set<String> customerSet = new TreeSet<String>();
		String finalCustomer = "";
		for (String customer : customers) {
			if (customerSet.add(customer)) {
				finalCustomer += customer + ",";
			}
		}
		finalCustomer = finalCustomer.substring(0, finalCustomer.length() - 1);
		salesInvoice.setCustomer(finalCustomer);

		String[] salesmans = salesInvoice.getSalesman().split(",");
		Set<String> salesmanSet = new TreeSet<String>();
		String finalSalesman = "";
		for (String salesman : salesmans) {
			if (salesmanSet.add(salesman)) {
				finalSalesman += salesman + ",";
			}
		}
		finalSalesman = finalSalesman.substring(0, finalSalesman.length() - 1);
		salesInvoice.setSalesman(finalSalesman);

		String[] orderAmounts = salesInvoice.getOrderAmount().split(",");
		double finalOrderAmount = 0;
		for (String orderAmount : orderAmounts) {
			if (!orderAmount.trim().isEmpty()) {
				finalOrderAmount += Double.parseDouble(orderAmount);
			}
		}
		salesInvoice.setOrderAmount(String.valueOf(finalOrderAmount));

		Tsalesinvoice tsalesinvoice = new Tsalesinvoice();
		BeanUtils.copyProperties(salesInvoice, tsalesinvoice);
		salesInvoiceDao.save(tsalesinvoice);
		params.clear();
		String[] orderNos = salesInvoice.getOrderNo().split(",");
		for (String orderNo : orderNos) {
			params.put("orderNo", orderNo);
			Tsalesorder tsalesorder = salesOrderDao.get("from Tsalesorder t where t.orderNo = :orderNo", params);
			if (tsalesorder != null) {
				tsalesorder.setInvoice("是");
			}
		}
	}

	@Override
	public void edit(SalesInvoice salesInvoice) throws Exception {
		String[] customers = salesInvoice.getCustomer().split(",");
		Set<String> customerSet = new TreeSet<String>();
		String finalCustomer = "";
		for (String customer : customers) {
			if (customerSet.add(customer)) {
				finalCustomer += customer + ",";
			}
		}
		finalCustomer = finalCustomer.substring(0, finalCustomer.length() - 1);
		salesInvoice.setCustomer(finalCustomer);

		String[] salesmans = salesInvoice.getSalesman().split(",");
		Set<String> salesmanSet = new TreeSet<String>();
		String finalSalesman = "";
		for (String salesman : salesmans) {
			if (salesmanSet.add(salesman)) {
				finalSalesman += salesman + ",";
			}
		}
		finalSalesman = finalSalesman.substring(0, finalSalesman.length() - 1);
		salesInvoice.setSalesman(finalSalesman);

		String[] orderAmounts = salesInvoice.getOrderAmount().split(",");
		double finalOrderAmount = 0;
		for (String orderAmount : orderAmounts) {
			if (!orderAmount.trim().isEmpty()) {
				finalOrderAmount += Double.parseDouble(orderAmount);
			}
		}
		salesInvoice.setOrderAmount(String.valueOf(finalOrderAmount));

		Tsalesinvoice tsalesinvoice = salesInvoiceDao.get(Tsalesinvoice.class, salesInvoice.getId());
		BeanUtils.copyProperties(salesInvoice, tsalesinvoice);
	}

	@Override
	public void delete(Integer id) {
		Tsalesinvoice tsalesInvoice = salesInvoiceDao.get(Tsalesinvoice.class, id);
		salesInvoiceDao.delete(tsalesInvoice);
		String[] orderNos = tsalesInvoice.getOrderNo().split(",");
		Map<String, Object> params = new HashMap<String, Object>();
		for (String orderNo : orderNos) {
			params.put("orderNo", orderNo);
			Tsalesorder tsalesorder = salesOrderDao.get("from Tsalesorder t where t.orderNo = :orderNo", params);
			if (tsalesorder != null) {
				tsalesorder.setInvoice("否");
			}
		}
	}

}
